<?php

class GmailLoader
{
	private $token;
	private $email;
	
	public function iniciarSesion($email,$pass)
	{
		$ch = curl_init("https://www.google.com/accounts/ClientLogin");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ($ch, CURLOPT_POST, 1); 
    	curl_setopt ($ch, CURLOPT_POSTFIELDS, "Email=$email&Passwd=$pass&service=cp&source=Wixet-WidgetContactosExternos-1"); 
    	$res = curl_exec($ch);
    	curl_close($ch);
    	$res = split("=",$res);
    	
    	if(trim($res[1]) == "BadAuthentication")
    		return false;
    	else
    	{
    		$this->email = $email;
    		$this->token=$res[3];
    		return true;
    	}
	}
	
	public function getListaContactos()
	{
		$ch = curl_init("http://www.google.com/m8/feeds/contacts/".$this->email."/full?max-results=1000");
	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: GoogleLogin auth='.$this->token));
		$xml = curl_exec($ch);
		
		$doc = new DOMDocument();
	    $doc->loadXML($xml);
	
		$contactos = array();
		$entradas = $doc->getElementsByTagName("entry");
		for ($actual = 0; $actual < $entradas->length; $actual++) {
			$contacto = array();
			$contacto['nombre'] = $entradas->item($actual)->getElementsByTagName("title")->item(0)->nodeValue;
		    $contacto['email'] = $entradas->item($actual)->getElementsByTagName("email")->item(0)->getAttribute("address");
		    if(strlen($contacto['nombre']) == 0)
		    	$contacto['nombre'] = $contacto['email'];
		    $contactos[] = $contacto;
		    
		}
		return $contactos;
	}
}